﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Routing;

using Polly;

using Api.Hub.Models;

namespace Api.Hub.Controllers
{
    public class PersonController : ApiController
    {
        static List<Person> persons = new List<Person>();

        static PersonController()
        {
            persons.Add(new Person() { Identity = 101, Name = "101", Age = 101, Sex = 1 });
            persons.Add(new Person() { Identity = 102, Name = "102", Age = 102, Sex = 1 });
            persons.Add(new Person() { Identity = 103, Name = "103", Age = 103, Sex = 1 });
            persons.Add(new Person() { Identity = 104, Name = "104", Age = 104, Sex = 1 });
        }

        public List<Person> Get(int? id = null)
        {
            var result = Policy.Handle<System.DivideByZeroException>().OrResult<List<Person>>(p => p.Count <= 2)
            .WaitAndRetry(1, retryCount =>
            {
                var tm = TimeSpan.FromSeconds(Math.Pow(2, retryCount));
                return tm;
            }).Execute(() =>
            {
                Console.WriteLine("进来了。。。。");
                var _persons = persons;
                int a = 10;
                int b = 0;
                int c = a / b;

                if (id.HasValue)
                {
                    var _id = id.GetValueOrDefault();
                    if (_id > 0)
                    {
                        _persons = persons.Where(f => f.Identity == _id).ToList();
                    }
                }

                return _persons;
            });

            return result;
        }

        [HttpPost]
        public HttpResponseMessage Post([FromBody]Person person)
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
            HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK);
            message.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return message;
        }
    }
}
